package com.bobo.util;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 图片下载器
 * @Auther: Swain
 * @Date: 2021/1/8 10:26
 * @Version 1.0.0
 */
public class ImageDowloader {


    public static void dowloadImage(String urlStr, String fileName) throws Exception {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("http.protocol.allow-circular-redirects", false);
        try {
            HttpResponse<String> inputStreamHttpResponse = Unirest
                    .get(urlStr)
                    .header("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)")
                    .queryString(paramMap)
                    .asString();
        } catch (Exception e) {
            try {
                String message = e.getCause().getCause().getMessage();
                String replace = message.replace("Invalid redirect URI: //", "").replace("（", "(").replace("）", ")");
                HttpResponse<InputStream> inputStreamHttpResponse = Unirest
                        .get("https://" + replace)
                        .header("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)")
                        .queryString(paramMap)
                        .asBinary();
                saveByInputStream(inputStreamHttpResponse.getBody(), fileName);
            } catch (Exception ex) {
                e.printStackTrace();
            }
        }
    }

    public static void saveByInputStream(InputStream inStream, String fileName) throws Exception {
        File image = new File(fileName);
        if (!image.exists()) {
            image.createNewFile();
        }
        FileOutputStream outStream = new FileOutputStream(image);
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        outStream.close();
    }

    public static String getCurrentDateTime(String format) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.now().format(formatter);
    }

}
